import 'dart:convert';

import 'package:flutter/foundation.dart';
import 'package:flutter/services.dart';

import 'china_push_platform_interface.dart';
import 'exception/register_exception.dart';

/// An implementation of [ChinaPushPlatform] that uses method channels.
class MethodChannelChinaPush extends ChinaPushPlatform {
  /// The method channel used to interact with the native platform.
  @visibleForTesting
  final methodChannel = const MethodChannel('china_push');

  String? brand = '';

  MethodChannelChinaPush() {
    methodChannel.setMethodCallHandler(flutterMethod);
  }

  Function(dynamic)? onNotificationClick;

  @override
  Future<String?> getPlatformVersion() async {
    final version =
        await methodChannel.invokeMethod<String>('getPlatformVersion');
    return version;
  }

  @override
  Future<dynamic> initPush() async {
    try {
      brand = await getManufacturer();
      return await methodChannel.invokeMethod('initPush');
    } on PlatformException catch (error) {
      throw RegisterException(
        error: "${error.message}",
        errorCode: "10086",
      );
    }
  }

  @override
  Future<String?> getRegId() async {
    return await methodChannel.invokeMethod('getRegId');
  }

  @override
  void enableLog(bool enable) {
    methodChannel.invokeMethod('enableLog',enable);
  }

  Future<dynamic> flutterMethod(MethodCall methodCall) async {
    switch (methodCall.method) {
      case 'onNotificationClick':
        debugPrint("通知点击9");
        notifyClickListener(methodCall.arguments);
        break;
      default:
        break;
    }
  }

  void notifyClickListener(dynamic data) {
    debugPrint("通知点击7");
    // if (data != null && data is String && data.isNotEmpty) {
    //   data = jsonDecode(data);
    // }
    // debugPrint("通知点击11");

    // onNotificationClick?.call(data);

    // 尝试将data作为JSON解码  
    try {  
      
        if (data != null && data is String && data.isNotEmpty) {  
            Map<String, dynamic> decodedData = jsonDecode(data) as Map<String, dynamic>;  
            debugPrint("通知点击11-1");
            onNotificationClick?.call(decodedData);  
        } else {  
            debugPrint("通知点击11-2");
            // 如果data不是非空字符串，则直接传递  
            onNotificationClick?.call(data);  
        }  
    } catch (e) {  

        // 如果jsonDecode抛出异常，则打印错误并传递原始字符串  
        print("Error decoding JSON: $e");  
        print("通知点击11-3 - ${brand?.toLowerCase()}",);
        if(brand?.toLowerCase() == 'mi' || brand?.toLowerCase() == 'xiaomi' || brand?.toLowerCase() == 'redmi' ) {
          onNotificationClick?.call(data);  
        }
    }  
  }

  @override
  void setNotificationClickListener(Function(dynamic) onNotificationClick) {
    debugPrint("通知点击8");
    this.onNotificationClick = onNotificationClick;
  }

  @override
  Future<String?> getManufacturer() async {
    return await methodChannel.invokeMethod('getManufacturer');
  }
}
